package com.ndp.fb.walle.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.enums.ErrorType;
import com.ndp.fb.rdb.model.Pager;
import com.ndp.fb.rdb.model.User;
import com.ndp.fb.rdb.model.customaudience.CustomAudienceTemplate;
import com.ndp.fb.util.ListUtil;
import com.ndp.fb.walle.business.CustomAudienceTemplateService;
import com.ndp.fb.walle.business.LooklikeAudienceTmplService;
import com.ndp.fb.walle.model.bo.customaudiencetemplate.result.CustomAudienceTemplateResult;
import com.ndp.fb.walle.model.vo.OutputResult;
import com.ndp.fb.walle.model.vo.PageResult;
import com.ndp.fb.walle.model.vo.customaudience.param.CountryRatio;
import com.ndp.fb.walle.model.vo.customaudience.param.CustomAudienceDelParam;
import com.ndp.fb.walle.model.vo.customaudience.param.LookALikeParam;
import com.ndp.fb.walle.model.vo.customaudience.param.QueryLookALikeParam;
import com.ndp.fb.walle.model.vo.customaudience.result.CountryRatioResult;
import com.ndp.fb.walle.util.ResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: Evan on 1/6/2016  11:59.
 * Email: evan.wan@ndpmedia.com
 */
@RequestMapping("/looklikeaudience")
@Controller
public class LooklikeAudienceTmplController {
    private final Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private LooklikeAudienceTmplService looklikeAudienceTmplService;

    @Autowired
    private CustomAudienceTemplateService customAudienceTemplateService;

    /**
     * 获取创建相似受众 源受众id
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "getOriginList")
    @ResponseBody
    public ResponseEntity<String> getOriginList(HttpServletRequest request) {
        logger.info("LooklikeAudienceTmplController getOriginList() begin.");
        ErrorType errorType = null;
        List<CustomAudienceTemplate> customAudienceTemplates = new ArrayList<>();
        try {
            User user = (User) request.getSession().getAttribute("user");
            customAudienceTemplates = customAudienceTemplateService.findByOrgId(user.getOrgId(), user.getTicket());
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("LooklikeAudienceTmplController getOriginList() error:", e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, customAudienceTemplates);
        logger.info("LooklikeAudienceTmplController getOriginList() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }


    /**
     * 相似受众列表
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public ResponseEntity<String> list(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("LooklikeAudienceTmplController list() begin.");
        ErrorType errorType = null;
        Map<String, Object> data = null;
        try {
            User user = (User) request.getSession().getAttribute("user");
            QueryLookALikeParam QueryLookALikeParam = JSON.parseObject(param, QueryLookALikeParam.class);
            int sizeNo = QueryLookALikeParam.getPSize() == null ? CommonConstants.DEFAULT_PAGE_SIZE_100 : QueryLookALikeParam.getPSize();
            int firstResult = QueryLookALikeParam.getCPage() == null ? 0 : (QueryLookALikeParam.getCPage() - 1) * sizeNo;
            // 查询列表
            Pager<CustomAudienceTemplateResult> customAudiencePager = customAudienceTemplateService.getLookAlikeList(QueryLookALikeParam, user, firstResult, sizeNo);
            // 计算分页结果
            long tSize = customAudiencePager.getTotalSize();
            float nrOfPages = (float) tSize / sizeNo;
            int tPage = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
            PageResult pageResult = new PageResult(tPage, QueryLookALikeParam.getCPage(), QueryLookALikeParam.getPSize(), tSize);

            // 封装响应结果
            data = new HashMap<>();
            data.put("customaudiences", customAudiencePager.getResultList());
            data.put("paginator", pageResult);

        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("CustomAudienceTemplateController findByPage error:", e);
        }

        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, data);
        logger.info("LooklikeAudienceTmplController list() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }


    /**
     * 相似受众-修改名称
     * 暂时未用到
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "updateName")
    @ResponseBody
    public ResponseEntity<String> updateName(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("LooklikeAudienceTmplController updateName() begin.");
        OutputResult outputResult = null;
        try {
            User user = (User) request.getSession().getAttribute("user");
            JSONObject parseObject = JSONObject.parseObject(param);
            Long templateId = parseObject.getLong("templateId");
            String audienceName = parseObject.getString("audienceName");
            //outputResult = customAudienceTemplateService.updateName(user, templateId, audienceName);
            return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
        } catch (Exception e) {
            logger.error("", e);
            outputResult = ResponseUtils.bulidOutputResult(ErrorType.INTERNAL_EXCEPTION, "fail");
        }
        logger.info("LooklikeAudienceTmplController updateName() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 创建相似受众
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "save")
    @ResponseBody
    public ResponseEntity<String> save(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("LooklikeAudienceTmplController save() begin.");
        OutputResult outputResult = null;
        try {
            User user = (User) request.getSession().getAttribute("user");
            LookALikeParam lookALikeParam = JSON.parseObject(param, LookALikeParam.class);
            int originType = lookALikeParam.getOriginType();
            Long originId = lookALikeParam.getOriginId();
            List<CountryRatio> countryRatioList = lookALikeParam.getCountryRatioList();

            //check状态太
            List<CountryRatioResult> existCountryRatioList = new ArrayList<>();
            for (CountryRatio countryRatio : countryRatioList) {
                CountryRatioResult countryRatioResult = new CountryRatioResult();
                BeanUtils.copyProperties(countryRatio, countryRatioResult);
                CustomAudienceTemplate template = looklikeAudienceTmplService.findCustomAudienceTemplateByoriginIdAndcountryCodeAndratio(originId, countryRatio.getCountry(), countryRatio.getRatio());
                if (template != null) {
                    countryRatioResult.setCustomAudienceTemplate(template);
                    existCountryRatioList.add(countryRatioResult);
                }
            }

            if (existCountryRatioList.size() > 0) {
                outputResult = ResponseUtils.bulidOutputResult(ErrorType.Exists_Country_Redio, existCountryRatioList);
            } else {
                if (originType == 2) {
                    looklikeAudienceTmplService.createLookALikeByPage(originId, countryRatioList, user);
                } else if (originType == 1) {
                    looklikeAudienceTmplService.createLookALikeByAudience(originId, countryRatioList, user);
                }
                outputResult = ResponseUtils.bulidOutputResult(null, existCountryRatioList);
            }
        } catch (Exception e) {
            logger.error("", e);
            outputResult = ResponseUtils.bulidOutputResult(ErrorType.INTERNAL_EXCEPTION, "fail");
        }
        logger.info("LooklikeAudienceTmplController save() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }

    /**
     * 根据受众模板id删除相似自定义受众
     * @param param
     * @param request
     * @return
     */
    @RequestMapping(value = "del")
    @ResponseBody
    public ResponseEntity<String> del(@RequestParam(value = "param", required = true) String param, HttpServletRequest request) {
        logger.info("LooklikeAudienceTmplController del() begin.");
        ErrorType errorType = null;
        Object result = null;
        User user = (User) request.getSession().getAttribute("user");
        try {
            CustomAudienceDelParam inParam = JSON.parseObject(param, CustomAudienceDelParam.class);
            if (inParam != null && ListUtil.isNotEmpty(inParam.getIds())){
                customAudienceTemplateService.delLookAlike(inParam, user.getTicket());
            } else{
                errorType = ErrorType.PARAM_EXCEPTION;
            }
        } catch (Exception e) {
            errorType = ErrorType.INTERNAL_EXCEPTION;
            logger.error("LooklikeAudienceTmplController del()", e);
        }
        OutputResult outputResult = ResponseUtils.bulidOutputResult(errorType, result);
        logger.info("LooklikeAudienceTmplController del() end.");
        return ResponseUtils.returnJsonWithUTF8(JSON.toJSONString(outputResult));
    }
}
